package map;

import java.util.Iterator;
import java.util.Map.Entry;
import java.util.function.BiConsumer;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.junit.Test;

public class ConcurrentHashMapDemo {
	@Test
	public void create() {
		ConcurrentHashMap map = new ConcurrentHashMap<>();
		// 给一个初始大小
		ConcurrentHashMap map2 = new ConcurrentHashMap<>(10);
		// 由其他map构建新map
		ConcurrentHashMap map3 = new ConcurrentHashMap<>(map);
	}
	
	@Test
	public void useful() {
		ConcurrentHashMap<Integer,String> map = new ConcurrentHashMap<>();
		// 1.添加一条
		map.put(1, "one");
		map.put(2, "two");
		map.put(3, "three");
		//put没有此key则add,  如果有相同的key,value会replace
		map.put(3, "three2");
	
		System.out.println(map);
		// 2.求元素个数
		System.out.println(map.size());
		// 3.根据key替换value
		map.replace(3, "three3");
		System.out.println(map);
		// 4.根据key得到value
		String string = map.get(2);
		// 5.判断是否包含key，value
		boolean containsKey = map.containsKey(1);
		boolean containsValue = map.containsValue("one");
		// 6.如果有此key返回value,否则返回后面的默认值
		String orDefault = map.getOrDefault(5, "five");
		// 7.根据key
		String removeValue = map.remove(1);
		boolean remove2 = map.remove(2, "two");
		// 8.清空
		map.clear();
	}
	
	@Test
	public void foreach() {
		ConcurrentHashMap<Integer,String> map = new ConcurrentHashMap<>();
		map.put(1, "one");
		map.put(2, "two");
		map.put(3, "three");
		
		//1.获取所有key返回是Set
		Set<Integer> keys = map.keySet();  // {1,2,3}
		// 得到迭代器
		Iterator<Integer> it = keys.iterator();
		while (it.hasNext()) {
			Integer key = it.next();
			System.out.println(key +":" + map.get(key));
		}
		System.out.println("---------------------");
		
		// 2.得到map的 Set<Entry<key,value>> ,  每一条key,value的组合== 一条Entry
		Set<Entry<Integer, String>> entrySet = map.entrySet();
		Iterator<Entry<Integer, String>> it2 = entrySet.iterator();
		while(it2.hasNext()) {
			Entry<Integer, String> entry = it2.next();
			System.out.println(entry.getKey() +":" + entry.getValue());
		}
		System.out.println("---------------------");
		
		// 3.foreach
		map.forEach(new BiConsumer<Integer, String>() {
			@Override
			public void accept(Integer key, String value) {
				System.out.println(key + ":" + value);
			}
		});
	}
}






















